﻿using AIConvertTool;
using FastGPT_Admin.Controller;
using FastGPT_Admin.Service;
using FastGPT_Admin.Setting;
using FastGPT_Admin.Tool;
using FastGPT_Admin.ViewModel;
using MongoDB.Bson;
using MongoDB.Driver.Core.Configuration;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using static System.Net.Mime.MediaTypeNames;

namespace FastGPT_Admin
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        static string iniPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.ini");
        IniFiles ini = new IniFiles(iniPath);

        AES256Helper AESHELPER = new AES256Helper();
        private string KEY = "123fastgpt1234567892024456789012"; // 必须是32个字符长
        private string IV = "123fastgpt123456"; // 必须是16个字符长

        public MainWindow()
        {
            InitializeSettings();
            InitializeComponent();

            ini.FindAndCreate(iniPath);
            GetIniFileItems();
        }
        public void InitializeSettings()
        {
            string DBSetting_URL = ini.IniReadValue("DBSetting", "URL");
            DBSetting_URL = AESHELPER.DecryptFromHex(DBSetting_URL, KEY, IV);
            AppSettings.GlobalSettingsInstance.ConnectionString = DBSetting_URL;
        }

        private void GetIniFileItems()
        {
            string UserSetting_PASSWORD = ini.IniReadValue("UserSetting", "PASSWORD");
            UserSetting_PASSWORD = AESHELPER.DecryptFromHex(UserSetting_PASSWORD, KEY, IV);

            string FastGPTSetting_URL = ini.IniReadValue("FastGPTSetting", "URL");
            FastGPTSetting_URL = AESHELPER.DecryptFromHex(FastGPTSetting_URL, KEY, IV);
            FastgptUrl.Text = FastGPTSetting_URL;

            string DBSetting_URL = ini.IniReadValue("DBSetting", "URL");
            DBSetting_URL = AESHELPER.DecryptFromHex(DBSetting_URL, KEY, IV);
            MongoDBConnectionString.Text = DBSetting_URL;

            if (string.IsNullOrEmpty(FastGPTSetting_URL) || string.IsNullOrEmpty(DBSetting_URL))
            {
                MessageBox.Show("请先填写后台设置信息");
            }

        }

        private void SaveSetting_Click(object sender, RoutedEventArgs e)
        {
            string FastGPTSetting_URL = FastgptUrl.Text;
            FastGPTSetting_URL = AESHELPER.EncryptToHex(FastGPTSetting_URL, KEY, IV);
            ini.IniWriteValue("FastGPTSetting", "URL", FastGPTSetting_URL);

            string DBSetting_URL = MongoDBConnectionString.Text;
            AppSettings.GlobalSettingsInstance.ConnectionString = DBSetting_URL;
            DBSetting_URL = AESHELPER.EncryptToHex(DBSetting_URL, KEY, IV);
            ini.IniWriteValue("DBSetting", "URL", DBSetting_URL);

            MessageBox.Show("保存成功\r如有问题，请删除Config.ini重新打开");
            RefreshDataViews();
        }

        private void RefreshDataViews()
        {
            ShowDataViewModel showDataViewModel = new ShowDataViewModel();
            string searchUser = SearchUsername.Text;
            string searchTeam = SearchTeamName.Text;
            showDataViewModel.RefreshData(searchUser, searchTeam);
            this.DataContext = showDataViewModel;
        }

        private void SignIn_Click(object sender, RoutedEventArgs e)
        {
            string signGroupName = SignGroupName.Text;
            string signUsername = SignUsername.Text;
            string signPassword = SignPassword.Text;
            if (!string.IsNullOrEmpty(signGroupName) && !string.IsNullOrEmpty(signUsername) && !string.IsNullOrEmpty(signPassword))
            {
                TeamsController teamsController = new TeamsController();
                string teamId = teamsController.CheckTeamsName(signGroupName);
                UsersController usersController = new UsersController();
                string userName = usersController.CheckUsersUsername(signUsername);
                if (teamId != "Null")
                {
                    if (userName == "Null")
                    {
                        DateTime localTime = DateTime.UtcNow.AddHours(8);
                        ObjectId userId = usersController.CreateUsers(new Users()
                        {
                            Username = signUsername,
                            Password = Hashing.HashStringX2(signPassword),
                            Status = "active",
                            Avatar = "/icon/human.svg",
                            PromotionRate = 10,
                            Timezone = "Asia/Shanghai",
                            CreateTime = localTime,
                            Version = 0
                        });
                        if (userId == ObjectId.Empty)
                        {
                            MessageBox.Show("创建用户失败，或者发生了异常。");
                        }
                        else
                        {
                            TeamMembersController teamMembersController = new TeamMembersController();
                            ObjectId TeamMembersId = teamMembersController.CreateTeamMembers(new TeamMembers()
                            {
                                TeamId = ObjectId.Parse(teamId),
                                UserId = userId,
                                Name = "Owner",
                                Role = "owner",
                                Status = "active",
                                CreateTime = localTime,
                                DefaultTeam = true
                            });

                            if (TeamMembersId == ObjectId.Empty)
                            {
                                MessageBox.Show("创建团队关联失败，或者发生了异常。");
                            }
                            else
                            {
                                MessageBox.Show("创建用户成功，快去使用吧\r点击下方登录跳转");
                            }
                            SignUsername.Text = "";
                            SignPassword.Text = "";
                            SignGroupName.Text = "";
                            RefreshDataViews();
                        }
                    } else
                    {
                        MessageBox.Show("用户名已存在");
                    }
                } else
                {
                    MessageBoxResult result = MessageBox.Show("团队名称不存在，是否创建？", "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);

                    if (result == MessageBoxResult.Yes)
                    {
                        if (userName == "Null")
                        {
                            DateTime localTime = DateTime.UtcNow.AddHours(8);
                            ObjectId userId = usersController.CreateUsers(new Users()
                            {
                                Username = signUsername,
                                Password = Hashing.HashStringX2(signPassword),
                                Status = "active",
                                Avatar = "/icon/human.svg",
                                PromotionRate = 15,
                                Timezone = "Asia/Shanghai",
                                CreateTime = localTime,
                                Version = 0
                            });
                            if (userId == ObjectId.Empty)
                            {
                                MessageBox.Show("创建用户失败，或者发生了异常。");
                            }
                            else
                            {
                                ObjectId newTeamId = teamsController.CreateTeams(new Teams()
                                {
                                    Name = signGroupName,
                                    OwnerId = userId,
                                    Avatar = "/icon/logo.svg",
                                    CreateTime = localTime,
                                    Balance = 999900000,
                                    Version = 0
                                });
                                if (newTeamId == ObjectId.Empty)
                                {
                                    MessageBox.Show("创建团队失败，或者发生了异常。");
                                }
                                else
                                {
                                    TeamMembersController teamMembersController = new TeamMembersController();
                                    ObjectId TeamMembersId = teamMembersController.CreateTeamMembers(new TeamMembers()
                                    {
                                        TeamId = newTeamId,
                                        UserId = userId,
                                        Name = "Owner",
                                        Role = "owner",
                                        Status = "active",
                                        CreateTime = localTime,
                                        DefaultTeam = true
                                    });

                                    if (TeamMembersId == ObjectId.Empty)
                                    {
                                        MessageBox.Show("创建团队关联失败，或者发生了异常。");
                                    }
                                    else
                                    {
                                        MessageBox.Show("创建用户成功，快去使用吧\r点击下方登录跳转");
                                    }
                                    SignUsername.Text = "";
                                    SignPassword.Text = "";
                                    SignGroupName.Text = "";
                                }
                            }
                        }
                        else
                        {
                            MessageBox.Show("用户名已存在");
                        }
                    }
                    else
                    {
                        // 用户点击了“取消”或关闭了消息框
                    }
                }
            } else
            {
                MessageBox.Show("请填写完整后再注册");
            }

            RefreshDataViews();
        }

        private void LogIn_Click(object sender, RoutedEventArgs e)
        {
            // 定义您想要打开的链接
            string url = FastgptUrl.Text;

            // 使用 ProcessStartInfo 来指定应在浏览器中打开链接
            ProcessStartInfo psi = new ProcessStartInfo
            {
                FileName = url,
                UseShellExecute = true
            };

            try
            {
                // 启动进程
                System.Diagnostics.Process.Start(psi);
            }
            catch (Exception ex)
            {
                // 处理可能发生的异常
                MessageBox.Show("无法打开链接：" + ex.Message);
            }
        }

        private void Refresh_Click(object sender, RoutedEventArgs e)
        {
            RefreshDataViews();
        }

        private void UsersListDataGrid_RadioButton_Checked(object sender, RoutedEventArgs e)
        {
            RadioButton radioButton = sender as RadioButton;
            if (radioButton != null)
            {
                DataGridRow row = VisualTreeHelpers.FindAncestor<DataGridRow>(radioButton);
                if (row != null)
                {
                    // 获取DataContext，即这一行的数据
                    Users user = row.DataContext as Users;
                    if (user != null)
                    {
                        // 现在你可以使用user对象来获取选中的行的数据
                        // 这里可以写上你想要执行的代码，比如：
                        UsersListSelectedID.Text = user.Id.ToString();
                        UsersListSelectedUsername.Text = user.Username;
                        if (user.Status == "active")
                        {
                            UsersListSelectedStatus.SelectedIndex = 1;
                        }
                        if (user.Status == "forbidden")
                        {
                            UsersListSelectedStatus.SelectedIndex = 2;
                        }
                    }
                }
            }
        }

        private void TeamsListDataGrid_RadioButton_Checked(object sender, RoutedEventArgs e)
        {
            RadioButton radioButton = sender as RadioButton;
            if (radioButton != null)
            {
                DataGridRow row = VisualTreeHelpers.FindAncestor<DataGridRow>(radioButton);
                if (row != null)
                {
                    // 获取DataContext，即这一行的数据
                    Teams team = row.DataContext as Teams;
                    if (team != null)
                    {
                        // 现在你可以使用user对象来获取选中的行的数据
                        // 这里可以写上你想要执行的代码，比如：
                        TeamsListSelectedID.Text = team.Id.ToString();
                        TeamsListSelectedName.Text = team.Name;
                    }
                }
            }
        }

        // 更新用户
        private void UpdateUser_Click(object sender, RoutedEventArgs e)
        {
            // 获取ComboBox的当前选中项的Content
            object selectedStatusObj = UsersListSelectedStatus.SelectedItem;
            string selectedStatus = "";
            if (selectedStatusObj != null)
            {
                selectedStatus = (selectedStatusObj as ComboBoxItem).Content as string;
            }
            if (UsersListSelectedID.Text != "" && UsersListSelectedUsername.Text != "" && selectedStatus != "")
            {
                UsersController usersController = new UsersController();
                string userName = usersController.CheckUsersUsername(UsersListSelectedUsername.Text);
                if (userName != null)
                {
                    Users updateUser = new Users()
                    {
                        Username = UsersListSelectedUsername.Text,
                        Status = selectedStatus
                    };
                    if (!string.IsNullOrEmpty(UsersListSelectedPassword.Text))
                    {
                        updateUser.Password = Hashing.HashStringX2(UsersListSelectedPassword.Text);
                    }

                    bool updateStatus = usersController.UpdateUsers(UsersListSelectedID.Text, updateUser);
                    if (updateStatus)
                    {
                        MessageBox.Show("更新成功。");
                        UsersListSelectedID.Text = "";
                        UsersListSelectedUsername.Text = "";
                        UsersListSelectedPassword.Text = "";
                        UsersListSelectedStatus.SelectedIndex = 0;
                        RefreshDataViews();
                    }
                    else
                    {
                        MessageBox.Show("更新失败。");
                    }
                } else
                {
                    MessageBox.Show("用户名已存在。");
                }
            } else
            {
                MessageBox.Show("请填写完整。");
            }

        }

        private void Search_KeyUp(object sender, KeyEventArgs e)
        {
            RefreshDataViews();
        }
    }

    // 辅助方法，用于在视觉树中查找指定类型的父元素
    public static class VisualTreeHelpers
    {
        public static T FindAncestor<T>(DependencyObject current) where T : DependencyObject
        {
            current = VisualTreeHelper.GetParent(current);

            while (current != null)
            {
                if (current is T)
                {
                    return (T)current;
                }
                current = VisualTreeHelper.GetParent(current);
            };
            return null;
        }
    }
}